var express = require('express');
var path=require('path');
var extend = require('extend');
var email=require('./email');
var router = express.Router();
var app = express();
var bodyParser = require('body-parser')
var book = require('./index');
var Transfer = require('./transfer');
var option = require('./option');
var port = process.env.PORT || 3200;
app.use(bodyParser());
router.get('/',function (req,res) {
    res.redirect('/index');
});
router.get('/index',function (req,res) {
    res.sendFile(path.resolve(__dirname, './index.html'), {
        headers: {
            'Content-Type': 'text/html; charset=UTF-8'
        }
    });
});
app.use('/',router);
app.use('/getBook',function (req, res) {
    res.setHeader('content-type', 'text/html; charset=utf-8');
    if(req.method==='POST'){
        option=extend({}, option, JSON.parse(req.body.op.replace(/\r/g,'').replace(/\n/g,'')));
        option.url = req.body.url;
    }else{
        option.url = req.query.url;
        option.titleText=req.query.title;
    }


    option.isServer=true;
    var index=0;
    option.logCallback = function (log) {
        if(index==0){
            res.write("<script>document.title='小说获取';window.timer=setInterval('document.body.scrollTop=document.body.offsetHeight',100)</script>")
        }
        index++;
        console.log(log);
        res.write(log + "<br/>");
    };
    option.resultCallback = function (title) {
        res.write('<a href="/downloadBook/'+title+'">点击下载 '+title+'</a><script>setTimeout("clearInterval(window.timer)",300)</script>');
        res.end();
    };
    option.errorCallback = function (err) {
        if(!!err&&!!err.indexOf&&'获取来源数据错误,未找到菜单数据,保存文件错误,错误次数超过1000次'.indexOf(err)>=0){
            email('306679829@qq.com','抓取程序错误',err+"<br/>"+JSON.stringify(option));
        }
        console.error(err);
        res.write("<div style='color:red'>" + err + "</div> <br/>请不要联系管理员306679829@qq.com");
        res.end();
    };
    book(option);
});
app.use('/downloadBook/:title',function (req, res) {
    if(req.params.title.indexOf('/')>=0||req.params.title.indexOf('\\')>=0){
        res.send('请输入合法地址');
        return;
    }
    res.download('./resource/' + req.params.title + '.txt');
});
module.exports = app.listen(port, function (err) {
    if (err) {
        console.log(err)
        return
    }
    var uri = 'http://localhost:' + port
    console.log('server listening at ' + uri + '\n');
})